<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap" :style="setTitleStyle">
					{{ $route.meta.title }}
				</div>
				<div class="flex-start-center-wrap">
					<el-checkbox
						v-model="isCustomDate"
						border
						size="small"
						class="item-gap"
						@change="onIsCustomDateChange"
					>自定义日期</el-checkbox>
					<div v-if="!isCustomDate" class="flex-start">
						<el-radio-group
							v-model="dateType"
							size="small"
							class="item-gap flex-center"
							@change="onDateTypeChange"
						>
							<el-radio-button
								v-for="dateItem in dateTypeList"
								:key="dateItem.id"
								:label="dateItem.id"
							>{{ dateItem.name }}</el-radio-button>
						</el-radio-group>
						<jk-select
							v-model="searchParams.fromShiftCode"
							:option-list="shiftList"
							size="small"
							placeholder="开始班次"
							class="search-bar-item-size1 margin-5-0 item-gap"
							@change="onHandleShift"
						></jk-select>
					</div>
					<div v-else class="flex-start">
						<jk-date-picker
							v-model="searchParams.fromDate"
							type="date"
							:disabled-future-time="true"
							:clearable="false"
							placeholder="班次开始日期"
							size="small"
							class="search-bar-item-size2 margin-5-0 item-gap"
						></jk-date-picker>
						<jk-select
							v-model="searchParams.fromShiftCode"
							:option-list="shiftList"
							size="small"
							placeholder="开始班次"
							class="search-bar-item-size1 margin-5-0 item-gap"
						></jk-select>
						<jk-date-picker
							v-model="searchParams.toDate"
							type="date"
							:disabled-future-time="true"
							:clearable="false"
							placeholder="班次结束日期"
							size="small"
							class="search-bar-item-size2 margin-5-0 item-gap"
						></jk-date-picker>
						<jk-select
							v-model="searchParams.toShiftCode"
							:option-list="shiftList"
							size="small"
							placeholder="结束班次"
							class="search-bar-item-size1 margin-5-0 item-gap"
						></jk-select>
					</div>
					<!--<jk-select v-model="searchParams.workshopId" :clearable="false" placeholder="区域" :option-list="workshopList" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onDateChange"></jk-select>-->
					<!-- <jk-date-picker v-else v-model="searchParams.belongDates" type="daterange" :disabled-future-time="true" :clearable="false" placeholder="日期" size="small" class="search-bar-item-size4 margin-5-0 item-gap" @change="onDateChange"></jk-date-picker>
                    <jk-select v-model="searchParams.shiftCode" :option-list="shiftList" size="small" placeholder="班次" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
                    <el-time-picker
                        v-model="pickerTime"
                        is-range
                        value-format="HH:mm:ss"
                        size="small"
                        range-separator="至"
                        style="width: 280px;"
                        class="margin-5-0 item-gap"
                        start-placeholder="班次开始时间"
                        end-placeholder="班次结束时间"
                    >
                    </el-time-picker> -->
					<!--<jk-select v-model="searchParams.duration" placeholder="时长排序" :option-list="[{id: 'asc', name:'正序'},{id: 'desc', name:'倒序'}]" size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>-->
					<jk-input
						v-model="searchParams.deviceNumber"
						class="search-bar-item-size2 margin-5-0 item-gap"
						placeholder="机台号"
						size="small"
						clearable
						@on-enter="onSearchBtn"
					/>
					<jk-select
						v-model="searchParams.position"
						label-key-name="id"
						placeholder="面位"
						:option-list="machineFaceList"
						size="small"
						class="search-bar-item-size1 margin-5-0 item-gap"
					></jk-select>
					<!--<jk-input v-model="searchParams.startIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="开始锭号" size="small" clearable @blur="onIngotNumberChange($event,'startIngotNo')" />-->
					<!--<jk-input v-model="searchParams.endIngotNo" class="search-bar-item-size1 margin-5-0 item-gap" placeholder="结束锭号" size="small" clearable @blur="onIngotNumberChange($event,'endIngotNo')" />-->
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<!-- <el-table
                :data="tableData"
                style="width: 100%"
                @sort-change="onSort"
            >
                <el-table-column
                    prop="brokenHeadCountForDevice"
                    label="日期"
                    sortable="custom"
                    width="180"
                >
                </el-table-column>
            </el-table> -->
			<jk-table
				ref="jkTable"
				border
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 20"
			>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template #header>
						<div v-if="item.keyName === 'deviceNumber'">
							<span>{{ item.title }}</span>
							<span></span>
						</div>
						<div v-else-if="item.keyName === 'position'">
							<span>{{ item.title }}</span>
							<span></span>
						</div>
						<div v-else-if="item.keyName === 'ingotNo'">
							<span>{{ item.title }}</span>
							<span></span>
						</div>
						<div v-else-if="item.keyName === 'totalBreakCount'" style="display: flex">
							<span>{{ item.title }}</span>
							<span
								style="
                                cursor: pointer;
                                display: flex;
                                align-items: center; "
								@click="toggleSort('total_break_count')"
							>
								{{ sortOrders.total_break_count === "asc" ? "⬆" : sortOrders.total_break_count === "desc" ? "⬇" : "⇅" }}
							</span>
						</div>
						<div v-else-if="item.keyName === 'maxBreakTime'" style="display: flex">
							<span>{{ item.title }}</span>
							<span
								style="
                                cursor: pointer;
                                display: flex;
                                align-items: center;"
								@click="toggleSort('max_break_time')"
							>
								{{ sortOrders.max_break_time === "asc" ? "⬆" : sortOrders.max_break_time === "desc" ? "⬇" : "⇅" }}
							</span>
						</div>
						<div v-else-if="item.keyName === 'totalBreakTime'" style="display: flex">
							<span>{{ item.title }}</span>
							<span
								style="
                                cursor: pointer;
                                display: flex;
                                align-items: center; "
								@click="toggleSort('total_break_time')"
							>
								{{ sortOrders.total_break_time === "asc" ? "⬆" : sortOrders.total_break_time === "desc" ? "⬇" : "⇅" }}
							</span>
						</div>
					</template>
					<template slot-scope="scope">
						<el-button
							v-if="item.keyName === 'totalBreakCount'"
							size="mini"
							type="primary"
							@click="onDetailBtn(scope.row)"
						>{{ scope.row[item.keyName] || '0' }}</el-button>
						<el-button
							v-else-if="item.keyName === 'maxBreakTime'"
							size="mini"
							type="primary"
							@click="onDetailBtn(scope.row, 'MINMAX')"
						>{{ scope.row[item.keyName] || '0' }}</el-button>
						<el-button
							v-else-if="item.keyName === 'totalBreakTime'"
							size="mini"
							type="primary"
							@click="onDetailBtn(scope.row)"
						>{{ scope.row[item.keyName] || '0' }}</el-button>
						<span v-else>{{ scope.row[item.keyName] || "" }}</span>
					</template>
				</vxe-column>
			</jk-table>
			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<detail-dialog
			:search-option-config="{
				shiftList,
				machineFaceList,
			}"
			:data-item="dataItem"
			:dialog-state="detailDialogState"
			@on-visible-change="onVisibleChangeOfDetailDialog"
		></detail-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '@/mixins/getMenuColumn';
    import handlerCache from '@/mixins/handler-cache';
    import mx from '../spindleBreakageReport/mx';
    import { spinSpinBrokenHeadGetBrokenHeadSortViewPage } from '../../../../api/statistic/spindleReports';
    import detailDialog from './detail-dialog.vue';

    export default {
        name: 'SpindleBreakageCountReport',
        components: { detailDialog },
        mixins: [calHeight, getMenuColumn, handlerCache, mx],
        data() {
            return {
                apiItem: {
                    page: spinSpinBrokenHeadGetBrokenHeadSortViewPage
                },
                sortField: '',
                scheduleShiftList: [],
                workshopList: [],
                tableLoading: true,
                dataItem: {},
                detailDialogState: false,
                tableData: [],
                totalCount: 0,
                pickerTime: [],
                sortOrders: {
                    total_break_count: null,
                    total_break_time: null,
                    max_break_time: null
                },
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    deviceNumber: undefined,
                    position: undefined,
                    ascField: null,
                    descField: null,
                    fromDate: undefined, // 开始时间
                    fromShiftCode: undefined, // 开始班制
                    toDate: undefined, // 结束时间
                    toShiftCode: undefined // 结束班制
                }
            };
        },
        // watch: {
        //     'searchParams.shiftCode': {
        //         handler(val) {
        //             const selectedShift = this.shiftList.find(i => i.id === val);
        //             if (selectedShift) {
        //                 const { beginHour, endHour } = selectedShift;
        //                 this.pickerTime = [beginHour, endHour]; // 直接赋值
        //             }
        //         },
        //         immediate: true
        //     }
        // },
        async mounted() {
            await this.getDependentData();
            await this.getCurrentShiftInfoRequest();
        },
        methods: {
            onVisibleChangeOfDetailDialog(e) {
                this.detailDialogState = e;
            },
            onDetailBtn(row, isRealTime) {
                this.dataItem = { ...row, ...JSON.parse(JSON.stringify(this.searchParams)) };
                this.dataItem.sortType = isRealTime || '';
                this.dataItem.descField = undefined;
                this.dataItem.ascField = undefined;
                // this.dataItem = JSON.parse(JSON.stringify(this.searchParams));
                // this.dataItem.deviceNumber = row.deviceNumber;
                // this.dataItem.shiftCode = row.shiftCode;
                // this.dataItem.shiftName = row.shiftName;
                this.detailDialogState = true;
            },
            toggleSort(field) {
                // 重置所有排序状态
                Object.keys(this.sortOrders).forEach((key) => {
                    if (key !== field) {
                        this.sortOrders[key] = null;
                    }
                });
                // 切换当前字段的排序状态
                if (
                    this.sortOrders[field] === null
                    // ||
                    // this.sortOrders[field] === 'desc'
                ) {
                    this.sortOrders[field] = 'asc';
                    this.searchParams.ascField = field;
                    this.searchParams.descField = null;
                } else if (this.sortOrders[field] === 'asc') {
                    this.sortOrders[field] = 'desc';
                    this.searchParams.ascField = null;
                    this.searchParams.descField = field;
                } else {
                    this.sortOrders[field] = null;
                    this.searchParams.ascField = null;
                    this.searchParams.descField = null;
                }
                this.getListRequest();
            },

            // mergeColMethod({ row, _rowIndex, column, visibleData }) {
            //     const mergeKeys = [
            //         ['deviceNumber'],
            //         ['deviceNumber', 'belongDate'],
            //         ['deviceNumber', 'belongDate', 'shiftName'],
            //         ['deviceNumber', 'belongDate', 'shiftName', 'screenShiftName'],
            //         [
            //             'deviceNumber',
            //             'belongDate',
            //             'shiftName',
            //             'screenShiftName',
            //             'totalBreakCount'
            //         ],
            //         [
            //             'deviceNumber',
            //             'belongDate',
            //             'shiftName',
            //             'screenShiftName',
            //             'totalBreakCount',
            //             'position'
            //         ],
            //         [
            //             'deviceNumber',
            //             'belongDate',
            //             'shiftName',
            //             'screenShiftName',
            //             'totalBreakCount',
            //             'position',
            //             'brokenHeadCountForPosition'
            //         ]
            //     ];
            //
            //     const mergeRule = mergeKeys.find(
            //         (keys) => keys[keys.length - 1] === column.property
            //     );
            //     if (!mergeRule || !row[column.property]) return;
            //
            //     const prevRow = visibleData[_rowIndex - 1];
            //     let nextRow = visibleData[_rowIndex + 1];
            //
            //     if (
            //         prevRow &&
            //         mergeRule.every((key) => prevRow[key] === row[key])
            //     ) {
            //         return { rowspan: 0, colspan: 0 };
            //     } else {
            //         let countRowspan = 1;
            //         while (
            //             nextRow &&
            //             mergeRule.every((key) => nextRow[key] === row[key])
            //         ) {
            //             nextRow = visibleData[++countRowspan + _rowIndex];
            //         }
            //         return countRowspan > 1
            //             ? { rowspan: countRowspan, colspan: 1 }
            //             : undefined;
            //     }
            // },
            // onDateChange() {
            //     this.$set(this.searchParams, 'shiftCode', '');
            //     this.scheduleShiftList = [];
            // },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            /** 查询列表 */
            getListRequest() {
                this.tableData = [];
                const { fromDate, toDate, deviceNumber } = this.searchParams;
                if (fromDate && toDate) {
                    this.tableLoading = true;
                    const params = JSON.parse(JSON.stringify(this.searchParams));
                    // params.belongDates = this.formatBelongDates(params.belongDates, params.shiftCode, this.pickerTime);
                    params.deviceNumber = deviceNumber && deviceNumber.trim();
                    return this.apiItem['page'](params).then((res) => {
                        this.tableLoading = false;
                        if (res.data.status === 200) {
                            this.tableData = res.data.res;
                            this.totalCount = res.data.count;
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '日期不能为空!');
                }
            }
        }
    };
</script>
<style lang="scss" scoped>

::v-deep .vxe-body--row span,
::v-deep .vxe-body--column {
    vertical-align: top !important;
}

</style>
